<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="database-type-management">
    <div class="query">
      <el-form inline ref="queryFormRef" :model="queryParams" label-width="100px" size="small">
        <el-form-item label="要素库名称:">
          <el-input style="width: 200px" v-model="queryParams.databaseName" placeholder="请输入要素库名称" />
        </el-form-item>
        <!-- <el-form-item label="场景/系统代码:">
          <el-input style="width: 200px" v-model="queryParams.fileName" placeholder="请输入文件名称" />
        </el-form-item> -->
        <el-form-item label="要素库层级:">
          <el-select v-model="queryParams.level" placeholder="请选择层级">
            <el-option v-for="item in typeList" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期:">
          <el-date-picker
            v-model="dateRangeCreateTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            style="width: 200px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="query_btns">
          <el-button size="small" type="primary" icon="search" @click="searchDatabase">查询</el-button>
          <el-button size="small" type="default" icon="refresh" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class="business-system-situation__main">
      <div class="left">
        <el-input size="small" v-model="matchName" placeholder="请输入关键字筛选" clearable style="margin-bottom: 10px" @keyup.enter="filterNode">
          <template #append>
            <el-button size="small" :icon="Search" @click="filterNode" />
          </template>
        </el-input>
        <el-tree 
          class="tree"
          @node-contextmenu="openMenu" 
          highlight-current 
          :indent="0"
          :default-expand-all="false"  
          :data="treeData" ref="tree" 
          node-key="id" 
          :props="defaultProps" 
          icon-class="el-icon-arrow-right"
          @node-click="handleNodeClick">
          <template #default="{ node,data }">
            <!-- <span class="custom-tree-node">
              <span class="node-title" v-if="node.level === 3">{{ data.mark }}({{ node.label }}) </span>
              <span class="node-title" v-else>{{ node.label }} </span>
            </span> -->
            <el-tooltip :disabled="tooltipVisible" effect="dark" :content="data.databaseName" placement="top">
              <div style="display: flex; align-items: center" @mouseover="handleNodeMouseOver">
                <img :src="getImageSrc(data)" alt="" style="height: 16px; width: 16px" />
                <span> {{ data.databaseName }}</span>
              </div>
            </el-tooltip>
          </template>
        </el-tree>

        <!-- 自定义右键菜单 -->
        <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
          <ul>
            <li v-if="menuLevel == 1" @click="handleMenuClick('add', 1, menuLevel)">
              <el-button size="small" link type="primary" icon="Plus">添加一级库</el-button>
            </li>
            <li @click="handleMenuClick('add', 2, menuLevel)">
              <el-button size="small" link type="primary" icon="Plus">添加二级库</el-button>
            </li>
            <li @click="handleMenuClick('edit', menuLevel)">
              <el-button size="small" link type="primary" icon="Edit">编辑</el-button>
            </li>
            <li @click="handleMenuClick('delete')">
              <el-button size="small" link type="primary" icon="Delete">删除</el-button>
            </li>
          </ul>
        </div>
      </div>
      <div class="right">
        <div class="table_div">
          <el-button size="small" type="primary" class="upload_btn" @click="handleAdd">添加要素库</el-button>
          <el-table :data="tableData" v-loading="loading">
            <el-table-column label="要素库名称" align="left" width="150" prop="databaseName"> </el-table-column>
            <el-table-column label="要素库层级" align="left" prop="level">
              <template #default="scope">{{ scope.row.level == 1 ? '一级库' : '二级库'}}</template>
            </el-table-column>
            <el-table-column label="所属父级库名称" align="left" prop="parentName">
              <template #default="scope">{{ scope.row.parentDatabaseName || '-' }}</template>
            </el-table-column>
            <el-table-column label="创建日期" align="left" prop="createTime" width="150" show-overflow-tooltip> 
              <template #default="scope">{{ scope.row.createTime }}</template>
            </el-table-column>
            <el-table-column label="描述" align="left" prop="description" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="left" width="200" fixed="right">
              <template #default="scope">
                <!-- <el-button size="small" link type="primary" icon="View" @click="handleOperate(scope.row, 'DETAIL')">详情</el-button> -->
                <el-button size="small" link type="primary" icon="Edit" @click="handleOperate(scope.row, 'EDIT')">编辑</el-button>
                <el-button size="small" link type="primary" icon="Delete" @click="handleOperate(scope.row, 'DELETE')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagenation">
            <!-- <el-pagination
              v-show="total > 0"
              layout="prev, pager, next,jumper"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              v-model:current-page="queryParams.pageNum"
              :total="total"
              @current-change="handleCurrentChange"
            /> -->
            <pagination
              v-show="total > 0"
              style="margin-top: 0;"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              :background="false"
              layout="total, sizes, prev, pager, next, jumper"
              @pagination="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <NewLibrary
    v-if="showView"
    :visible="showView"
    :rowId="typeItemId"
    :operateType="operateType"
    :operateTitle="operateTitle"
    :parentId="parentId"
    :level="level"
    :typeList="typeList"
    @handleEvent="handleEvent"
   />
</template>
<script setup name="libraryManagement">
import database from '@/assets/images/modelEstablish/database.svg';
import { Search } from '@element-plus/icons-vue';
import NewLibrary from './component/NewLibrary.vue';
// import Contrast from '../../compare/components/Contrast.vue';
const typeList = [{label: '一级库', value: 1}, {label: '二级库', value: 2}]
import { getDicts } from '@/api/system/dict/data';
import { downloadFile } from '@/utils/index';
import { getDatabaseTypeList, getTreeList, deleteDatabaseType } from '@/api/databaseManagement';
// import { bdfFileFunc } from "../fileDownload.js";
const treeData = ref([]);
const loading = ref(false);
const showView = ref(false);
const typeItemId = ref(null);
const level = ref(null);
const operateType = ref('');
const dialogType = ref('');
const operateTitle = ref('');
const parentId = ref(0);
const defaultProps = {
  children: 'children',
  label: 'databaseName'
};
const menuVisible = ref(false);
const mentRemoveCheck = ref(false);
const menuStyle = ref({
  left: 0,
  top: 0
});
const tableData = ref([]);
const total = ref(0);
const dateRangeCreateTime = ref(['', '']);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  isAsc: 'asc',
  level: "",
  databaseName: '',
  startCreateTime: '',
  endCreateTime: ''
})
const formRef = ref(null);
const wrapper = ref(null);
const showAdd = ref(false);
const formData = ref({ name: '', mark: '', taskDefault: '' });
const nodeContent = ref(null);
const editFlag = ref(false);
const menuLevel = ref(null);
const matchName = ref('');
const view = (row) => {
  bdfItem.value = row
  showBdf.value = true;
}
// 初始化图标
const getImageSrc = (data) => {
  return database;
};
const handleNodeMouseOver = (node) => {
  var target = node.target;
  let textLength = target.clientWidth;
  const nodeContent = target.closest('.el-tree-node__content');
  const containerWidth = nodeContent.clientWidth; // 获取包含 padding+border 的完整宽度
  console.log(textLength, containerWidth)
  if (textLength + 55 < containerWidth) {
    tooltipVisible.value = true;
  } else {
    tooltipVisible.value = false;
  }
};
const handleEvent = (data) => {
  showView.value = false;
  if (data?.type === 'refresh') {
    queryTreeMenu('');
    doQuery();
  } 
};
const filterNode = () => {
  // if (!value) return true;
  treeData.value = [];
  queryTreeMenu(matchName.value);
};
const handleOperate = (row, type) => {
  if (type == 'EDIT') {
    typeItemId.value = row.id;
    operateType.value = type;
    operateTitle.value = '编辑要素库类型';
    level.value = null;
    parentId.value = null;
    showView.value = true;
  } else {
    ElMessageBox.confirm(`是否确认删除要素库类型【${row.databaseName}】？`, `提示`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteDatabaseType(row.id)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            queryTreeMenu('');
            doQuery();
          }
        })
        .catch(() => {
          // ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
        });
    });
  }
}
const handleAdd = () => {
  typeItemId.value = null;
  operateType.value = 'ADD';
  operateTitle.value = '新增要素库类型';
  level.value = null;
  parentId.value = undefined;
  showView.value = true;
}
// 节点点击右侧列表更新
const handleNodeClick = (data, TreeNode) => {
  if (TreeNode.level == 1) {
    queryParams.value.id = data.id;
    // queryParams.value.type = 0;
  } else if (TreeNode.level == 2) {
    queryParams.value.id = data.id;
    // queryParams.value.type = 1;
  } 
  queryParams.value.pageNum = 1;
  doQuery();
}

const handleDelete = (row) => {}
const handleCurrentChange = (val) => {
  // queryParams.value.pageNum = val.page;
  doQuery();
};  
const searchDatabase = () => {
  queryParams.value.id = null;
  doQuery();
}
const doQuery = () => {  
  loading.value = true;
  tableData.value = [];
  queryParams.value.startCreateTime = dateRangeCreateTime.value[0];
  queryParams.value.endCreateTime = dateRangeCreateTime.value[1];
  getDatabaseTypeList(queryParams.value).then((res) => {
    if (res.rows) {
      loading.value = false;
      tableData.value = res.rows;
      total.value = res.total;
    }
  })
  .catch(() => {
    loading.value = false;
  }).finally(() => {
    loading.value = false;
  });
};
const doReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    isAsc: 'asc',
    databaseName: "",
    level: "",
    createName: "",
    startCreateTime: '',
    endCreateTime: ''
  };
  dateRangeCreateTime.value = ['', ''];
  doQuery();
};
const handleClick = (event) => {
  // 检查点击是否发生在外部
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};
const handleMenuClick = (command, type, menuLevel) => {
  if (command === 'add') {
    typeItemId.value = null;
    operateType.value = 'ADD';
    dialogType.value = type;
    operateTitle.value = `新增要素库${type == 1 ? '一级库' : '二级库'}`;
    level.value = type;
    parentId.value = type == 1 ? undefined : menuLevel == 1 ? nodeContent.value.id : nodeContent.value.parentId;
    showView.value = true;
  }
  if (command === 'edit') {
    typeItemId.value = nodeContent.value.id;
    operateType.value = 'EDIT';
    dialogType.value = type;
    level.value = type;
    operateTitle.value = '编辑要素库类型';
    parentId.value = type == 1 ? undefined : menuLevel == 1 ? nodeContent.value.id : nodeContent.value.parentId;
    showView.value = true;
  }
  if (command === 'delete') {    
    ElMessageBox.confirm(`是否确认删除此要素库类型？`, `删除【${nodeContent.value.databaseName}】`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteDatabaseType(nodeContent.value.id)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            queryTreeMenu();
            doQuery();
          }
        })
        .catch(() => {
          // ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
        });
    });
  }
  menuVisible.value = false;
};

// 右键点击
const openMenu = (event, data, node, element) => {
  menuLevel.value = node.level;
  nodeContent.value = data;
  // 显示菜单
  menuVisible.value = true;
  // 阻止默认的右键菜单显示
  event.preventDefault();
  // 设置菜单的位置
  menuStyle.value.left = 180 + 'px';
  menuStyle.value.top = event.clientY - 182 + 'px';
};

const queryTreeMenu = (name) => {
  getTreeList({databaseName: name}).then((res) => {
    if (res) {
      treeData.value = res|| []
    }
  });
};
onMounted(() => {
  queryTreeMenu('');
  doQuery();
  window.addEventListener('click', handleClick);
});
onUnmounted(() => {
  window.removeEventListener('click', handleClick);
});
</script>
<style lang="less" scoped>
.database-type-management {
  padding-top: 10px;
  font-size: 12px;
  padding: 20px;
  // height: calc(100vh - 190px);
  // overflow: auto;
  .business-system-situation__main {
    display: flex;
  }
  .left {
    width: 300px;
    position: relative;
    border-right: 1px solid #ebebeb;
    // padding: 10px;
    padding-bottom: 20px;
    height: calc(100vh - 215px);
    overflow: auto;
    .title {
      font-weight: 600;
    }
    .custom-menu {
      position: absolute;
      background-color: #fff;
      border: 1px solid #ebebeb;
      border-radius: 3px;
      width: 120px;
      z-index: 1000;
      font-size: 12px;
      ul {
        margin: 0;
        padding: 5px 0;
        list-style: none;
        font-size: 12px;
      }
      ul li {
        padding: 3px 15px;
        cursor: pointer;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
      ul li:hover {
        background-color: #eee;
      }
    }
    :deep(.el-tree-node__label) {
      font-size: 12px;
    }
    .custom-tree-node{
      font-size: 12px;
    }
  }
  .right {
    padding: 10px 10px 10px 20px;
    height: calc(100vh - 215px);
    overflow: auto;
    flex: 1;
    .pagenation {
      display: flex;
      justify-content: end;
      padding: 10px;
    }
  }
  .disable{
    color:#d9d9d9;
  }
}
/* 树形结构节点添加连线 */
:deep .tree {
  .el-tree-node {
    position: relative;
    padding-left: 10px;
    /* 缩进量 */
  }

  .el-tree-node__children {
    padding-left: 15px;
    /* 缩进量 */
  }

  /* 竖线 */
  .el-tree-node::before {
    content: '';
    height: 100%;
    width: 1px;
    position: absolute;
    left: -3px;
    top: -26px;
    border-width: 1px;
    border-left: 1px dashed #52627c;
  }

  /* 当前层最后一个节点的竖线高度固定 */
  .el-tree-node:last-child::before {
    height: 40px;
    /* 可以自己调节到合适数值 */
  }

  /* 横线 */
  .el-tree-node::after {
    content: '';
    width: var(--after-width, 16px);
    height: 20px;
    position: absolute;
    left: -3px;
    top: 13px;
    border-width: 1px;
    border-top: 1px dashed #52627c;
  }

  /* 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了 */
  & > .el-tree-node::after {
    border-top: none;
  }

  & > .el-tree-node::before {
    border-left: none;
  }

  /* 展开关闭的icon */
  .el-tree-node__expand-icon {
    font-size: 12px;
    /* 叶子节点（无子节点） */
    &.is-leaf {
      color: transparent;
      /* 也可以去掉 */
      // display: none;
      width: 1px;
    }
  }
}
</style>